import { createRequire } from 'module';
import { Permissions } from '../all/all.js'

/**
 * 全局
 */
const require = createRequire(import.meta.url);
const { exec } = require('child_process');
const _path = process.cwd() + './plugins/spacexiao_minecraft/'
let timer;

/**
 * 管理员
 */
export class admin extends plugin {
	constructor() {
		super({
			name: '管理|更新插件',
			dsc: '管理和更新代码',
			event: 'message',
			priority: 400,
			rule: [
				{
					reg: '^(#|/)晓宇宙(插件)?(强制)?更新',
					fnc: 'checkout',
				},
			],
		});
	}

	async checkout(e) {
		let qq = e.user_id
		let yanzheng = await Permissions(qq, 5, e)
		if (!yanzheng) return;
		const isForce = this.e.msg.includes('强制');
		let command = `git -C ${_path} pull --no-rebase`
		if (isForce) {
			command = `git -C ${_path} reset --hard HEAD && ${command}`
			this.e.reply('正在执行强制更新操作，请稍等');
		} else {
			this.e.reply('正在执行更新操作，请稍等');
		}
		const that = this;
		//这是为了防止下面的那条太长了!
		let say = `spacexiao_minecraft更新成功！`
		say += `\n正在尝试重新启动Yunzai以应用更新...`
		exec(command, { cwd: `${_path}` }, function (error, stdout, stderr) {
			if (/(Already up[ -]to[ -]date|已经是最新的)/.test(stdout)) {
				that.e.reply('目前已经是最新版spacexiao_minecraft了~');
				return;
			}
			if (error) {
				that.e.reply('spacexiao_minecraft更新失败！\nError code: ' + error.code + '\n' + error.stack + '\n 请稍后重试。');
				return;
			}
			that.e.reply(say);
			timer && clearTimeout(timer);
			timer = setTimeout(async () => {
				try {
					let data = JSON.stringify({
						isGroup: !!that.e.isGroup,
						id: that.e.isGroup ? that.e.group_id : that.e.user_id,
					});
					let cm = 'pnpm run start';
					if (process.argv[1].includes('pm2')) {
						cm = 'pnpm run restart';
					} else {
						await that.e.reply('当前为前台运行，重启将转为后台...');
					}
					exec(cm, (error, stdout, stderr) => {
						if (error) {
							redis.del(that.key);
							that.e.reply('自动重启失败，请手动重启以应用新版spacexiao_minecraft。\nError code: ' + error.code + '\n' + error.stack + '\n');
							logger.error(`重启失败\n${error.stack}`);
						} else if (stdout) {
							logger.mark('重启成功，运行已转为后台');
							logger.mark('查看日志请用命令：pnpm run log');
							logger.mark('停止后台运行命令：pnpm stop');
							process.exit();
						}
					});
				} catch (error) {
					redis.del(this.key);
					let e = error.stack ?? error;
					that.e.reply(`重启yunzai操作失败！\n${e}`);
				}
			}, 1000);
		});
		return true;
	}
}
